package com.jthink.admin.menu;

import com.jthink.common.model.Menu;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;

import java.util.Date;
import java.util.List;

public class MenuAdminService {
    private Menu dao = new Menu();

    public String getNameById(int id) {
        return Db.queryStr("SELECT name FROM menu where id=?", id);
    }

    public Menu getByRelative(String relativeTable, Object relativeId) {

        return dao.findFirst("SELECT * FROM menu where relativeTable=? and relativeId=?", relativeTable, relativeId);
    }

    public int deleteByRelative(String relativeTable, Object relativeId) {
        return Db.delete("delete from menu where relativeTable=? and relativeId=?", relativeTable, relativeId);
    }

    private Ret validate(Menu menu) {
        if (menu == null) {
            return Ret.fail("菜单 信息不能为 null");
        }
        if (StrKit.isBlank(menu.getName())) {
            return Ret.fail("菜单 名称 不能为空");
        }
        if (null != menu.getId() && menu.getId().equals(menu.getPid())){
            return Ret.fail("父菜单 不能选择当前菜单本身");
        }
        return null;

    }

    public List<Menu> findAll() {
        return dao.find("SELECT * FROM menu order by weight asc");
    }

    /**
     * 创建
     */
    public Ret save(Menu menu) {
        Ret ret = validate(menu);
        if (ret != null) {
            return ret;
        }
        menu.setCreated(new Date());
        menu.setUpdated(menu.getCreated());
        menu.save();
        return Ret.ok("创建成功");
    }

    public Menu edit(int id) {
        return dao.findById(id);
    }

    /**
     * 更新
     */
    public Ret update(Menu menu) {
        Ret ret = validate(menu);
        if (ret != null) {
            return ret;
        }
        menu.setUpdated(new Date());
        menu.update();

        return Ret.ok("更新成功");
    }

    /**
     * 删除
     */
    public Ret deleteById(int id) {
        dao.deleteById(id);
        return Ret.ok( "删除成功");
    }
}
